#include "movie.h"

static int fifo_fd;									//管道文件的文件描述符
static char movie_buf[128] = {0};					//拼接字符串buf
static int movie_flag      =  0;					//视频的标志位


static int movie_flagSSS      =  0;	
//1、创建并打开管道文件
int open_pipe_movie(void)
{
	//a、创建管道文件
	if(access("/tmp/fifo", F_OK)==-1)
	{
		int ret=mkfifo("/tmp/fifo", 0777);
		if(ret == -1)
		{
			printf("create fifofile error\n");
			return -1;
		}
	}
	//b、打开管道文件
	fifo_fd=open("/tmp/fifo", O_RDWR);
	if (fifo_fd == -1)
	{
		printf("open fifofile error\n");
		return -2;
	}
	return 0;
}


//2、播放视频(指定播放视频、播放位置、播放长宽)
int play_movie(char *moviepath, int lcd_x, int lcd_y, int length, int width)
{
	if(movie_flag == 0)
	{
		open_pipe_movie();							//打开管道文件
		bzero(movie_buf, sizeof(movie_buf));		//1、清空字符串

		sprintf(movie_buf, "mplayer -slave -quiet -input file=/tmp/fifo -geometry %d:%d -zoom -x %d -y %d %s &", 
			    lcd_x, lcd_y, length, width, moviepath);
													//2、拼接字符串于buf中
		system(movie_buf);							//3、执行buf里面的shell命令
		
		movie_flag = 1;
	}
	return 0;
}


//3、发送命令控制视频
int  send_cmd_movie(int cmd)
{
	bzero(movie_buf, sizeof(movie_buf));		//清空字符串
	if(cmd == 1)								//1、结束视频
	{
		//strcpy复制字符串到buf中
		strcpy(movie_buf, "quit 0\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
		//strlen函数算出char型buf中的字符串长度
		close_pipe_movie();
		movie_flag = 0;
		usleep(500000);
	}
	if(cmd == 2)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "quit 0\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 3)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "seek -10\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 4)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "pause\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 5)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "seek 10\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 6)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "volume 10\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 7)								//2、暂停/继续视频
	{
		strcpy(movie_buf, "volume -10\n");
		write(fifo_fd, movie_buf, strlen(movie_buf));
	}
	if(cmd == 8)								//2、暂停/继续视频
	{
		if(movie_flagSSS == 0)
		{
			strcpy(movie_buf, "mute 1\n");
			write(fifo_fd, movie_buf, strlen(movie_buf));
			movie_flagSSS =1;
		}
		else{
			strcpy(movie_buf, "mute 0\n");
			write(fifo_fd, movie_buf, strlen(movie_buf));
			movie_flagSSS =0;
		}
		
	}
	return 0;
}


//4、关闭管道文件
int close_pipe_movie(void)
{
	close(fifo_fd);
	return 0;
}